package cn.blnp.net.flowable.task.service.property;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.DelegateHelper;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.stereotype.Component;

/**
 * <h3></h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/5/13 10:30
 */
@Slf4j
public class CalculationDelegateExpressionFieldInjected implements JavaDelegate {

    @Setter
    private Expression inventoryCheckResult;

    /**
     *  <p>
     *   &emsp;&emsp;这个委托代理类中没有定义流程定义的服务任务中声明要注入的另外两个属性totalAmount和description，在COMPATIBILITY模式下这样做会抛出异常，而在MIXED模式下这样做是允许的。
     *   代码中totalAmount和description的获取，使用了org.flowable.engine.delegate.DelegateHelper工具类的getFieldExpression()方法获取表达式，直接读取BpmnModel并在方法执行
     *   时创建表达式，因此是线程安全的。同时可知，这种方式与注入Expression在服务任务定义上是相同的。
     *  </p>
     **/
    @Override
    public void execute(DelegateExecution execution) {
        //读取注入的inventoryCheckResult字段值
        String inventoryCheckResultStr = (String) inventoryCheckResult.getValue(execution);
        if ("库存不足".equals(inventoryCheckResultStr)) {
            log.error("库存不足！");
            return;
        }
        //读取注入的totalAmount字段值
        Expression totalAmountNumExpression = DelegateHelper
                .getFieldExpression(execution, "totalAmount");
        double totalAmountNum = (double) totalAmountNumExpression.getValue(execution);
        //读取注入的description字段值
        Expression descriptionExpression = DelegateHelper
                .getFieldExpression(execution, "description");
        String descriptionStr = (String) descriptionExpression.getValue(execution);
        //从流程变量中获取unitPrice、quantity的值
        double unitPrice = (double) execution.getVariable("unitPrice");
        int quantity = (int) execution.getVariable("quantity");
        log.info("单价：{}，数量：{}，总价：{}", unitPrice, quantity, totalAmountNum);
        log.info("描述信息：{}", descriptionStr);
        //将totalAmount放入流程变量中
        execution.setVariable("totalAmount", totalAmountNum);
    }
}
